<?php

namespace App\Models;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
use CodeIgniter\Validation\ValidationInterface;

class User_model extends Model
{
    protected $DBGroup = 'default';
    protected $table = 'users';
    protected $primaryKey = 'id';
    protected $returnType = 'array';

    protected $allowedFields = [
        'username','password','email','telephone','avatar',
        "profile","male",'location','birthday',
        'start_learn_time','end_learn_time','school','subject','qualification',
        'start_work_time','company','position','industry',
        'follow_count','fans_count',"zan_count"
    ];

    // 构造函数
    public function __construct()
    {
        // 父类 自动使用默认配置组连接数据库
        parent::__construct();
        $this->db = \Config\Database::connect();
    }

    // 查询用户
    public function query_user($field, $value): array{
        $builder = $this->db->table($this->table);
        $builder->where([$field => $value]);
        return $builder->get()->getResultArray();
    }

    // 添加用户
    public function insert_user( $user_info){
        $builder = $this->db->table($this->table);
        return  $builder->insert([
            'username' => $user_info['username'],
            'email' => $user_info['email'],
            'telephone' => $user_info['telephone'],
            'password' => $user_info['password'],
            'avatar'=>$user_info['avatar']
        ]);
    }


    // 用户登录
    public function login($username, $password){
        $sql = "SELECT * FROM users WHERE username = ? AND password = ?";
        $query = $this->db->query($sql,[$username, $password]);
        if($query){
            $row = $query->getRowArray();
            if(isset($row)) {
                return $row;
            }
        }
        return false;
    }

    // 拿到用户信息通过id
    // ["username", "email", "avatar"]
    public function getUser($where_field,$value,$select_fields){
        $builder = $this->db->table($this->table);
        $builder->select($select_fields);

         return $builder->getWhere([$where_field=>$value],1)->getRowArray();
    }

    // 更新头像
    public function update_data($id,$update_data){
        if(!$this -> getUser("id",$id,["username"]))
            return false;
        $builder = $this->db->table($this->table)->where('id', $id);
        return $builder->update($update_data);
    }
}